package com.lilinling.yinzhi.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lilinling.common.exception.BizCodeEnum;
import com.lilinling.common.utils.*;
import com.lilinling.yinzhi.user.dao.UserDao;
import com.lilinling.yinzhi.user.entity.UserEntity;
import com.lilinling.yinzhi.user.exception.AccountExsitException;
import com.lilinling.yinzhi.user.exception.EmailExsitException;
import com.lilinling.yinzhi.user.exception.MobileExsitException;
import com.lilinling.yinzhi.user.exception.NicknameExsitException;
import com.lilinling.yinzhi.user.service.UserService;
import com.lilinling.yinzhi.user.vo.UserLoginVo;
import com.lilinling.yinzhi.user.vo.UserRegisterVo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     */
    @Override
    public void register(@Valid UserRegisterVo userRegisterVo) {

        String nickname = userRegisterVo.getNickname();
        String account = userRegisterVo.getAccount();
        String password = userRegisterVo.getPassword();
        String mobile = userRegisterVo.getMobile();
        UserDao userDao = this.baseMapper;
        UserEntity entity = new UserEntity();

        //检查账号和手机号是否唯一
        checkNicknameUnique(userRegisterVo.getNickname());
        checkAccountUnique(userRegisterVo.getAccount());
        checkMobileUnique(userRegisterVo.getMobile());

        //注册
        entity.setMakerId(0L);
        entity.setNickname(nickname);
        entity.setAccount(account);
        entity.setMobile(mobile);
        entity.setHeader("https://yinzhi-hello.oss-cn-guangzhou.aliyuncs.com/%E5%A4%B4%E5%83%8F.png");

        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        entity.setPassword(encode);
        userDao.insert(entity);
    }

    /**
     * 登录
     */
    @Override
    public String login(@Valid UserLoginVo vo) {

        String account = vo.getAccount();
        String password = vo.getPassword();

        //校验用户名是否存在
        UserDao userDao = this.baseMapper;
        UserEntity entity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("account",account)
                .or().eq("mobile",account));
        if(entity == null){
            //登陆失败
            throw new RRException(BizCodeEnum.ACCT_NULL_EXCEPTION.getMsg(),BizCodeEnum.ACCT_NULL_EXCEPTION.getCode());
        }else {
            //从数据库获取password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password,passwordDb);
            if (matches){
                //登录，生成token
                JwtInfo info = new JwtInfo();
                info.setId(entity.getId());
                info.setMakerId(entity.getMakerId());
                info.setNickname(entity.getNickname());
                info.setHeader(entity.getHeader());

                String jwtToken = JwtUtils.getJwtToken(info, 3600);
                return jwtToken;
            }else{
                return null;
            }
        }
    }

    /**
     * 邮件验证
     */
    @Override
    public void checkEmailUnique(String email) throws EmailExsitException{
        UserDao userDao = this.baseMapper;
        Integer count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("email", email));
        if(count > 0){
            throw new EmailExsitException();
        }
    }

    /**
     * 账号验证
     */
    @Override
    public void checkAccountUnique(String account) throws AccountExsitException{
        UserDao userDao = this.baseMapper;
        Integer count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("account", account));
        if(count > 0){
            throw new AccountExsitException();
        }

    }

    /**
     * 用户名验证
     */
    @Override
    public void checkNicknameUnique(String nickname) throws NicknameExsitException{
        UserDao userDao = this.baseMapper;
        Integer count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("nickname", nickname));
        if(count > 0) {
            throw new NicknameExsitException();
        }
    }

    /**
     * 手机号验证
     */
    @Override
    public void checkMobileUnique(String mobile) throws MobileExsitException{
        UserDao userDao = this.baseMapper;
        Integer count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("mobile", mobile));
        if(count > 0) {
            throw new MobileExsitException();
        }
    }
}